﻿//Force setting jQuery support cross domain.
//This line mostly has effective in IE
jQuery.support.cors = true;

// variable for audience page
var arrAudience = new Array()  // store all audience item get from getListAudience 


/*** get data from service  ****/
var arrData = new Array(); // all infomation get from service
var selectedRowKey = ""; // row's id is current selected in list
$(document).ready(function () {
    userId = readCookie("userId");
    RoleType = readCookie("RoleType");
    CampId = readCookie("CampId");
    if (userId == "") {
        window.location.href = 'login';
    }
    // get list audience
    function getListAudience() {
        var url;
        arrData.splice(0, arrData.length);
        if (RoleType == "2") {
            url = 'group/list.json?userid=' + userId;
        }
        else {
            url = 'group/list.json?userid=' + userId + '&campaignid=' + CampId;
        }
        $.getJSON(gb_servicePath + url,
                function (json) {
                    if (json.StatusCode == 200) {
                        $(".list_row_users").find("img").hide();
                        $(".list_row_users .rows_users").show();
                        $.each(json.ReturnData, function (i, val) {
                            arrAudience[val.ID] = val;
                            var o = $("#list_row_users_temp").clone();
                            $(o).css("display", "block");
                            if (i % 2 == 1) {
                                $(o).addClass("users_alt");
                            }
                            $(o).attr("id", val.ID);

                            $(o).find(".col_audience_name").html(val.Name);
                            $(o).find(".col_audience_description").html(val.Desc);
                            //$(o).find(".col_audience_Type").html(val.Audiencelevel);
                            $(o).find(".col_audience_Type").html("Sub-group");
                            //$(o).find(".col_audience_enterprise").html(val.Campaign.Brand.Company.Name);
                            //$(o).find(".col_audience_Brand").html(val.Campaign.Brand.Name);
                            $(o).find(".col_audience_campaign").html(val.Campaign.Name);
                            $(o).find(".i_edit").attr("id", val.ID);
                            $("#list_row_users").append(o);

                            //Fill data to Data Object
                            var oo = new Object();
                            //Id
                            oo.id = val.ID;
                            //Audicen Name 
                            oo.audienceName = val.Name;
                            //Description
                            oo.description = val.Desc;
                            //Campaing
                            oo.campaign = val.Campaign.Name;
                            //Audience Type
                            oo.audienceType = "Sub-group";
                            arrData.push(oo);

                        });
                        SortAudienceFilter("audienceName", 1);
                        $('.list_row_users').jScrollPane({ animateScroll: true });
                    }
                    addEventForRowUser();
                });
    }

    // Sort Audience List function
    function SortAudienceFilter(str, index) {

        arrData = arrData.objSort(str, index);
        $(".list_row_users").find(".rows_users").each(function () {
            $(this).remove();
        });

        for (var i = 0; i < arrData.length; i++) {
            var o = $("#list_row_users_temp").clone();
            $(o).css("display", "block");
            if (i % 2 == 1) {
                $(o).addClass("users_alt");
            }
            $(o).attr("id", arrData[i].id);

            $(o).find(".col_audience_name").html(arrData[i].audienceName);
            $(o).find(".col_audience_description").html(arrData[i].description);
            //$(o).find(".col_audience_Type").html(val.Audiencelevel);
            $(o).find(".col_audience_Type").html(arrData[i].audienceType);
            //$(o).find(".col_audience_enterprise").html(val.Campaign.Brand.Company.Name);
            //$(o).find(".col_audience_Brand").html(val.Campaign.Brand.Name);
            $(o).find(".col_audience_campaign").html(arrData[i].campaign);
            $(o).find(".i_edit").attr("id", arrData[i].ID);
            if ($("#list_row_users").find(".jspPane").size() == 0) {
                $("#list_row_users").append(o);
            } else {
                $("#list_row_users").find(".jspPane").append(o);
            }
        }
        $('#list_row_users').jScrollPane({ animateScroll: true });
        addEventForRowUser();
    }
    //get all enterprise
    function getListEnterprise() {
        $.getJSON(gb_servicePath + 'enterprise/list.json',
                function (json) {
                    if (json.StatusCode == 200) {
                        $.each(json.ReturnData, function (i, val) {
                            $("select.ddenterprise").find("option").remove();
                            var o = $("<option id='" + val.Id + "' value='" + val.Name + "'>" + val.Name + "</option>")
                            $("select.ddenterprise").append(o);
                            if (i == 0) {
                                $(".ddenterprise").find(".customStyleSelectBoxInner").html(val.Name);
                                getListBrand(val.Id);
                            }
                        });
                    }
                });
    }

    //get brand by enterprise id
    function getListBrand(enterpriseid) {
        $.getJSON(gb_servicePath + 'brand/list.json?enterpriseid=' + enterpriseid,
                function (json) {
                    if (json.StatusCode == 200) {
                        $.each(json.ReturnData, function (i, val) {
                            $("select.ddbrand").find("option").remove();
                            var o = $("<option id='" + val.Id + "' value='" + val.Name + "'>" + val.Name + "</option>")
                            $("select.ddbrand").append(o);
                            if (i == 0) {
                                $(".ddbrand").find(".customStyleSelectBoxInner").html(val.Name);
                                getListCampaign(val.Id);
                            }
                        });
                    }
                });
    }

    //get campaign by brand id
    function getListCampaign(brandid) {
        $.getJSON(gb_servicePath + 'campaign/list/summary.json?brandid=' + brandid,
                function (json) {
                    if (json.StatusCode == 200) {
                        $("select.ddcampaign").find("option").remove();
                        $.each(json.ReturnData, function (i, val) {
                            var o = $("<option id='" + val.Id + "' value='" + val.Name + "'>" + val.Name + "</option>")
                            $("select.ddcampaign").append(o);
                            if (i == 0) {
                                $(".ddcampaign").find(".customStyleSelectBoxInner").html(val.Name);
                            }
                        });
                    }
                });
    }
    /*** End  get data from service  ****/


    // After add/modify row(audience instance ) of list_row_user , need to readd event listener for all row 
    function addEventForRowUser() {
        $('.rows_users').click(function () {
            $('.rows_users').removeClass('rows_user_hover');
            $(this).addClass('rows_user_hover');
            $('.bar').addClass('hide');
            $(this).find('.bar').removeClass('hide');
            $('.list_row_users').jScrollPane({ animateScroll: true });

            $('.box_super_admin').addClass('hide');
            $('#view_audience').removeClass('hide');

            //filldata to summary box
            var id = $('.rows_user_hover').attr("id");

            $.ajax({
                url: gb_servicePath + '/group/ID/' + id + '.json',
                crossDomain: "true",
                type: "GET",
                contentType: 'application/json; charset=utf-8',
                traditional: true,
                data: "",
                dataType: 'json',
                success: function (data) {
                    if (data.StatusCode == 200) {
                        var audience = data.ReturnData;
                        $(".summary_name").html(audience.Name);
                        $(".summary_description").html(audience.Desc);
                        $(".summary_campaign").html(audience.Campaign.Name);
                        $(".summary_audienceType").html('Sub-group');

                        $('.btn_close').click(function (e) {
                            $("#view_audience").addClass('hide');
                            $('.bar').addClass('hide');
                            $('.rows_user_hover').removeClass('rows_user_hover');
                            return false;
                        });
                    }
                },
                error: function (jqXHR, textStatus, xerror) {
                    if (isBug) {
                        alert("Error in authenticateduser/list/summary.json ->" + xerror);
                    }
                }
            });


        });
    }

    //delete item in list_row_user
    function deleteRow() {
        //find item active hover --> remove it --> reorder css
        $(".rows_user_hover").remove();
        //close all edit
        $('.box_super_admin').addClass('hide');

    }

    //when select enterprise change
    function onDllenterpriseChange() {

    }

    $('.cus_textarea').corner("5px");
    $('body').addClass('has-js');
    $('.label_check_ip').click(function () {
        setupLabel();
    });
    setupLabel();

    getListAudience();
    getListEnterprise();
    $('#list_row_users_temp').css("display", "none");
    $('select.select_long').customStyle();
    $('.ddenterprise').change(function () {
        onDllenterpriseChange();
    });

    //sort function
    $("#audience_tbl_header").find("img").css("visibility", "hidden");

    //Bind event click Sort By Audience Name
    $("#btAudienceName").click(function () {
        //Sort
        SortAudienceFilter("audienceName", -1 * parseInt($("#btAudienceName").attr("sort")));

        $("#btAudienceName").attr("sort", -1 * parseInt($("#btAudienceName").attr("sort")));

        $("#btAudienceName").find("img").css("visibility", "visible");
        $("#btDescription").find("img").css("visibility", "hidden");
        $("#btCampaign").find("img").css("visibility", "hidden");
        $("#btAudicenType").find("img").css("visibility", "hidden");

        if ($("#btAudienceName").attr("sort") == 1) {
            $("#btAudienceName").find("img").rotate(180);
        } else {
            $("#btAudienceName").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Audience Name
    //Bind event click Sort By Audience Description
    $("#btDescription").click(function () {
        //Sort
        SortAudienceFilter("description", -1 * parseInt($("#btDescription").attr("sort")));

        $("#btDescription").attr("sort", -1 * parseInt($("#btDescription").attr("sort")));

        $("#btDescription").find("img").css("visibility", "visible");
        $("#btAudienceName").find("img").css("visibility", "hidden");
        $("#btCampaign").find("img").css("visibility", "hidden");
        $("#btAudicenType").find("img").css("visibility", "hidden");

        if ($("#btDescription").attr("sort") == 1) {
            $("#btDescription").find("img").rotate(180);
        } else {
            $("#btDescription").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Audience Description
    //Bind event click Sort By Audience Campaign
    $("#btCampaign").click(function () {
        //Sort
        SortAudienceFilter("campaign", -1 * parseInt($("#btCampaign").attr("sort")));

        $("#btCampaign").attr("sort", -1 * parseInt($("#btCampaign").attr("sort")));

        $("#btCampaign").find("img").css("visibility", "visible");
        $("#btAudienceName").find("img").css("visibility", "hidden");
        $("#btDescription").find("img").css("visibility", "hidden");
        $("#btAudicenType").find("img").css("visibility", "hidden");

        if ($("#btCampaign").attr("sort") == 1) {
            $("#btCampaign").find("img").rotate(180);
        } else {
            $("#btCampaign").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Audience Campaign
    //Bind event click Sort By Audience Campaign
    $("#btAudicenType").click(function () {
        //Sort
        SortAudienceFilter("audienceType", -1 * parseInt($("#btAudicenType").attr("sort")));

        $("#btAudicenType").attr("sort", -1 * parseInt($("#btAudicenType").attr("sort")));

        $("#btAudicenType").find("img").css("visibility", "visible");
        $("#btAudienceName").find("img").css("visibility", "hidden");
        $("#btDescription").find("img").css("visibility", "hidden");
        $("#btCampaign").find("img").css("visibility", "hidden");

        if ($("#btAudicenType").attr("sort") == 1) {
            $("#btAudicenType").find("img").rotate(180);
        } else {
            $("#btAudicenType").find("img").rotate(0);
        }
    });
    // End Bind event click Sort By Audience Campaign

    $('#btnSavelNew').click(function () {
        var id = $('.rows_user_hover').attr("id");
        var url;
        var audience = new Object();
        audience.name = $('#input_name').val();
        audience.description = $('#input_description').val();
        audience.campaignid = $(".ddcampaign").find("option:selected").attr("id");
        audience.audiencelevel = "2";

        if ($(this).hasClass('new')) {
            url = "/group/create.json";
        }
        if ($(this).hasClass('update')) {
            url = "/group/update/" + id + ".json";
        }

        $.ajax({
            url: gb_servicePath + url,
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(audience),
            "dataType": 'json',
            success: function (data) {
                $(".list_row_users").find("img").show();
                $(".list_row_users .rows_users").hide();
                getListAudience();
                //alert(data.ReturnData.ID);
            },
            error: function (jqXHR, textStatus) {

                alert("Error in GEMAPI//group/create.json");

            }
        });

    });
});
function showNew() {
    $('.box_super_admin').addClass('hide');
    $('#new_audience').removeClass('hide');
    $('.header_box_super_admin').html('New Audience');
    $('#btnSavelNew').removeClass('update').addClass('new');
    $('#new_audience').addClass('nobg');
    $('.div_countries').jScrollPane({ animateScroll: true });
    $('#btnCancel').click(function (e) {
        $("#new_audience").addClass('hide');
        $('.rows_user_hover .bar').addClass('hide');
        $('.rows_users').removeClass('rows_user_hover');
        return false;
    });
    resetForm();
}
function resetForm() {
    $('#input_name').val('');
    $('#input_description').val('');

}

function showEdit() {
    $('.box_super_admin').addClass('hide');
    $('#new_audience').removeClass('hide');
    var id = $('.rows_user_hover').attr("id");
    $.ajax({
        url: gb_servicePath + '/group/ID/' + id + '.json',
        crossDomain: "true",
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        traditional: true,
        data: "",
        dataType: 'json',
        success: function (data) {
            if (data.StatusCode == 200) {
                var audience = data.ReturnData;
                $('#input_name').val(audience.Name);
                $('#input_description').val(audience.Desc);
                $(".ddcampaign").val(audience.Campaign.Name).attr("selected", "selected");
                $('span.ddcampaign .customStyleSelectBoxInner').html(audience.Campaign.Name);


                $('.btn_close').click(function (e) {
                    $("#view_audience").addClass('hide');
                    $('.bar').addClass('hide');
                    $('.rows_user_hover').removeClass('rows_user_hover');
                    return false;
                });
            }
        },
        error: function (jqXHR, textStatus, xerror) {
            if (isBug) {
                alert("Error in authenticateduser/list/summary.json ->" + xerror);
            }
        }
    });

    $('.header_box_super_admin').html('Edit Audience');
    $('#btnSavelNew').removeClass('new').addClass('update');
    $('#new_audience').removeClass('nobg');
    $('.div_countries').jScrollPane({ animateScroll: true });
    $('#btnCancel').click(function (e) {
        $("#new_audience").addClass('hide');
        $('.rows_user_hover .bar').addClass('hide');
        $('.rows_users').removeClass('rows_user_hover');
        return false;
    });

}